import RSATool from '../../lib/RSATool';
import configTool from '../../com/configTool';

function TokenAuthorityHandler() {
    return async (ctx: any, next: Function) => {
        const token_get = ctx.request.query?.token;
        const token_body = ctx.request.body?.token;
        const token_header = ctx.request.header?.token;
        const token = token_get || token_body || token_header;

        await next();
        return;

        const url = decodeURI(ctx.request.url);
        if (url.includes('/AuthorizeServer/login')
            || url.startsWith('/MapResources/')
            || url.startsWith('/Resources/')
            || url.startsWith('/Web')
            || url.startsWith('/favicon.ico')
            || url.startsWith('/test/testConnect')
            || url.startsWith('/droneServer/getRtcSubscriberToken')
            || url.startsWith('/droneServer/getRtcPublisherToken')
            || url.startsWith('/DroneFile')
            || url.startsWith('/VGEEarth-SDK')
            || url.startsWith('/phone.html')
            || url === '/') {
            await next();
        } else if (token) {
            const ip = ctx.request.ip;
            const verify = RSATool.verifyJWT(token, ip, configTool.baseConfig.privateDer);

            if (verify) {
                await next();
            } else {
                ctx.status = 401;
                ctx.response.body = {code: 401, message: 'Token 错误', desc: `Token 错误`};
            }
        } else {
            ctx.response.status = 401;
            ctx.response.body = {
                code: 401, message: '参数缺少 Token', desc: `参数缺少 Token`
            };
        }
    };
}


export default TokenAuthorityHandler;
